<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getSalaryPayList, getSalaryPayDetail } from '@/api/salary'
import { getOrganizationOptions } from '@/api/system'

const searchForm = ref({
  keyword: '',
  month: null,
  department: undefined,
  status: undefined,
})

const columns = [
  { title: '批次号', dataIndex: 'batch', key: 'batch', width: 150 },
  { title: '员工编号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '姓名', dataIndex: 'name', key: 'name', width: 100 },
  { title: '发放月份', dataIndex: 'month', key: 'month', width: 120 },
  { title: '应发合计', dataIndex: 'totalPay', key: 'totalPay', width: 120 },
  { title: '扣款合计', dataIndex: 'deduction', key: 'deduction', width: 120 },
  { title: '实发金额', dataIndex: 'actualPay', key: 'actualPay', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref([])
const loading = ref(false)

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
})

// 详情弹窗相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref({})

// 部门选项
const departmentOptions = ref([])

// 获取部门选项
const fetchDepartmentOptions = async () => {
  try {
    const response = await getOrganizationOptions()
    if (response && response.list) {
      departmentOptions.value = response.list.map((item) => ({
        value: item.value,
        label: item.label,
      }))
    } else {
      departmentOptions.value = []
    }
  } catch (error) {
    console.error('获取部门选项失败:', error)
    departmentOptions.value = []
  }
}

// 获取薪酬发放列表
const fetchPayList = async (page = 1, pageSize = 10) => {
  loading.value = true
  try {
    const params = {
      page,
      pageSize,
    }

    // 处理 keyword 参数
    if (searchForm.value.keyword && searchForm.value.keyword.trim()) {
      params.keyword = searchForm.value.keyword.trim()
    }

    // 处理 month 参数
    if (searchForm.value.month) {
      if (typeof searchForm.value.month === 'string') {
        params.month = searchForm.value.month
      } else if (searchForm.value.month.format) {
        params.month = searchForm.value.month.format('YYYY-MM')
      }
    }

    // 处理 department 参数
    if (searchForm.value.department) {
      params.department = searchForm.value.department
    }

    // 处理 status 参数
    if (searchForm.value.status) {
      params.status = searchForm.value.status
    }

    // 移除 undefined 的字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getSalaryPayList(params)

    // 处理返回的分页数据
    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id || `${item.batch}-${Math.random()}`, // 使用 id 或 batch 作为 key
      }))
      // 更新分页信息
      pagination.value.total = response.total || 0
      pagination.value.current = response.page || page
      pagination.value.pageSize = response.pageSize || pageSize
    } else {
      dataSource.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取薪酬发放列表失败:', error)
    dataSource.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchPayList(pag.current, pag.pageSize)
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchPayList(1, pagination.value.pageSize)
}

const handleReset = () => {
  searchForm.value = {
    keyword: '',
    month: null,
    department: undefined,
    status: undefined,
  }
  pagination.value.current = 1
  fetchPayList(1, pagination.value.pageSize)
}

const handleExport = () => {
  // TODO: 调用导出接口
  message.info('导出功能待实现')
}

// 获取薪酬明细
const fetchPayDetail = async (record) => {
  detailLoading.value = true
  try {
    // 使用 batch 参数调用接口
    if (!record.batch) {
      message.error('缺少批次号信息')
      return
    }

    const response = await getSalaryPayDetail(record.batch)

    // 处理返回的数据
    if (response && response.list && Array.isArray(response.list) && response.list.length > 0) {
      // 从列表中查找当前记录的明细（根据 batch 匹配，如果列表中有多条，使用第一条）
      const detailItem = response.list[0]

      // 将接口返回的数据映射到详情弹窗需要的格式
      detailData.value = {
        code: detailItem.code || '-',
        name: detailItem.name || '-',
        month: detailItem.month || response.month || '-',
        batch: detailItem.batch || response.batch || record.batch,
        department: detailItem.department || detailItem.organization || '-',
        position: detailItem.position || '-',
        payDate: detailItem.payDate || '-',
        // 应发项目
        baseSalary: detailItem.baseSalary || 0,
        positionSalary: detailItem.positionSalary || 0,
        performanceBonus: detailItem.performanceBonus || 0,
        allowance: detailItem.allowance || 0,
        overtimePay: detailItem.overtimePay || 0,
        otherIncome: detailItem.otherIncome || 0,
        totalPay: detailItem.totalPay || record.totalPay || 0,
        // 扣款项目（注意接口返回的是 socialSecurity，不是 socialInsurance）
        socialInsurance: detailItem.socialSecurity || detailItem.socialInsurance || 0,
        housingFund: detailItem.housingFund || 0,
        tax: detailItem.tax || 0,
        otherDeduction: detailItem.otherDeduction || 0,
        deduction: detailItem.deduction || record.deduction || 0,
        // 实发
        actualPay: detailItem.actualPay || record.actualPay || 0,
        // 状态
        status: detailItem.status || record.status,
        remark: detailItem.remark || '',
      }
    } else {
      // 如果没有返回数据，使用列表中的基本信息
      detailData.value = {
        code: record.code || '-',
        name: record.name || '-',
        month: record.month || '-',
        batch: record.batch,
        department: record.department || record.organization || '-',
        position: record.position || '-',
        payDate: record.payDate || '-',
        baseSalary: record.baseSalary || 0,
        positionSalary: record.positionSalary || 0,
        performanceBonus: record.performanceBonus || 0,
        allowance: record.allowance || 0,
        overtimePay: record.overtimePay || 0,
        otherIncome: record.otherIncome || 0,
        totalPay: record.totalPay || 0,
        socialInsurance: record.socialSecurity || record.socialInsurance || 0,
        housingFund: record.housingFund || 0,
        tax: record.tax || 0,
        otherDeduction: record.otherDeduction || 0,
        deduction: record.deduction || 0,
        actualPay: record.actualPay || 0,
        status: record.status,
        remark: record.remark || '',
      }
    }
  } catch (error) {
    console.error('获取薪酬明细失败:', error)
    // 如果接口失败，使用列表中的基本信息
    detailData.value = {
      code: record.code || '-',
      name: record.name || '-',
      month: record.month || '-',
      batch: record.batch,
      department: record.department || record.organization || '-',
      position: record.position || '-',
      payDate: record.payDate || '-',
      baseSalary: record.baseSalary || 0,
      positionSalary: record.positionSalary || 0,
      allowance: record.allowance || 0,
      totalPay: record.totalPay || 0,
      socialInsurance: record.socialSecurity || record.socialInsurance || 0,
      housingFund: record.housingFund || 0,
      tax: record.tax || 0,
      deduction: record.deduction || 0,
      actualPay: record.actualPay || 0,
      status: record.status,
      remark: record.remark || '',
    }
  } finally {
    detailLoading.value = false
  }
}

// 打开详情弹窗
const handleViewDetail = async (record) => {
  detailVisible.value = true
  await fetchPayDetail(record)
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  detailData.value = {}
}

onMounted(() => {
  fetchDepartmentOptions()
  fetchPayList(1, pagination.value.pageSize)
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">薪酬发放查询</h1>
      <p class="page-desc">提供薪酬发放记录的查询功能，支持按月份查询发放记录和薪酬明细</p>
    </div>

    <div class="page-content">
      <div class="search-card">
        <div class="search-form">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input v-model:value="searchForm.keyword" placeholder="员工编号/姓名" allow-clear />
            </a-col>
            <a-col :span="6">
              <a-date-picker
                v-model:value="searchForm.month"
                picker="month"
                placeholder="发放月份"
                style="width: 100%"
              />
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.department"
                placeholder="所属部门"
                allow-clear
                style="width: 100%"
              >
                <a-select-option
                  v-for="option in departmentOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.status"
                placeholder="状态"
                allow-clear
                style="width: 100%"
              >
                <a-select-option value="已发放">已发放</a-select-option>
                <a-select-option value="待复核">待复核</a-select-option>
                <a-select-option value="已锁定">已锁定</a-select-option>
              </a-select>
            </a-col>
          </a-row>
          <div class="search-actions">
            <a-space>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
              <a-button @click="handleExport">导出</a-button>
            </a-space>
          </div>
        </div>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="['totalPay', 'deduction', 'actualPay'].includes(column.key)">
              <span style="font-weight: 500"
                >¥{{ (record[column.key] || 0).toLocaleString() }}</span
              >
            </template>
            <template v-if="['code', 'name', 'month'].includes(column.key)">
              <span>{{ record[column.key] || '-' }}</span>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '已发放'
                    ? 'green'
                    : record.status === '待复核'
                      ? 'orange'
                      : 'blue'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleViewDetail(record)"
                >查看明细</a-button
              >
              <a-button type="link" size="small">下载薪酬条</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 薪资明细弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="薪酬明细"
      width="800px"
      :footer="null"
      @cancel="handleCloseDetail"
    >
      <a-spin :spinning="detailLoading">
        <div v-if="!detailLoading && Object.keys(detailData).length > 0" class="detail-content">
          <a-card title="基本信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="员工编号">{{ detailData.code }}</a-descriptions-item>
              <a-descriptions-item label="姓名">{{ detailData.name }}</a-descriptions-item>
              <a-descriptions-item label="所属部门">{{
                detailData.department
              }}</a-descriptions-item>
              <a-descriptions-item label="职位">{{ detailData.position }}</a-descriptions-item>
              <a-descriptions-item label="发放月份">{{ detailData.month }}</a-descriptions-item>
              <a-descriptions-item label="发放日期">{{ detailData.payDate }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-tag
                  :color="
                    detailData.status === '已发放'
                      ? 'green'
                      : detailData.status === '待复核'
                        ? 'orange'
                        : 'blue'
                  "
                >
                  {{ detailData.status }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="应发项目" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="基本工资"
                >¥{{ detailData.baseSalary?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="岗位工资"
                >¥{{ detailData.positionSalary?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="绩效奖金"
                >¥{{ detailData.performanceBonus?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="各类补贴"
                >¥{{ detailData.allowance?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="加班费"
                >¥{{ detailData.overtimePay?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="其他收入"
                >¥{{ detailData.otherIncome?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="应发合计" :span="2">
                <span class="total-amount">¥{{ detailData.totalPay?.toLocaleString() }}</span>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="扣款项目" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="社会保险"
                >¥{{ detailData.socialInsurance?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="住房公积金"
                >¥{{ detailData.housingFund?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="个人所得税"
                >¥{{ detailData.tax?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="其他扣款"
                >¥{{ detailData.otherDeduction?.toLocaleString() }}</a-descriptions-item
              >
              <a-descriptions-item label="扣款合计" :span="2">
                <span class="deduction-amount">¥{{ detailData.deduction?.toLocaleString() }}</span>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="实发金额" class="detail-section" :bordered="false">
            <div class="actual-pay-section">
              <div class="actual-pay-label">实发金额</div>
              <div class="actual-pay-amount">¥{{ detailData.actualPay?.toLocaleString() }}</div>
            </div>
            <div v-if="detailData.remark" class="remark-section">
              <div class="remark-label">备注：</div>
              <div class="remark-text">{{ detailData.remark }}</div>
            </div>
          </a-card>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.search-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.detail-content {
  padding: 8px 0;
}

.detail-section {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.detail-section :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.detail-section :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.detail-section :deep(.ant-card-body) {
  padding: 24px;
}

.detail-section :deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background: #f5f5f5;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.deduction-amount {
  font-size: 16px;
  font-weight: 600;
  color: #ff3b30;
}

.actual-pay-section {
  text-align: center;
  padding: 32px 0;
  border: 2px solid #34c759;
  border-radius: 8px;
  background: rgba(52, 199, 89, 0.05);
}

.actual-pay-label {
  font-size: 14px;
  color: #86868b;
  margin-bottom: 12px;
}

.actual-pay-amount {
  font-size: 32px;
  font-weight: 700;
  color: #34c759;
  letter-spacing: 1px;
}

.remark-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.remark-label {
  font-size: 13px;
  color: #86868b;
  margin-bottom: 8px;
}

.remark-text {
  font-size: 14px;
  color: #1d1d1f;
  line-height: 1.6;
}
</style>
